import json
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponseRedirect
from django.core.cache import cache


# 判断是否登录才能进入的网址
class Redirect(MiddlewareMixin):
    # 请求中间件
    def process_request(self, request):
        # 需要登录后才能进入的页面列表
        url_list = ['backend', 'addarticle', 'editarticle', 'delarticle', 'addcover', 'MYarticle']
        if not request.user.is_authenticated and request.path_info.split('/')[1] in url_list:
            return HttpResponseRedirect('/login')


# 用来处理将post请求的json数据统一转为字典类型
class Md1(MiddlewareMixin):
    # 请求中间件
    def process_request(self, request):
        # 判断请求方式为post并且请求内容类型为json时，对json数据进行处理
        if request.method != 'GET' and request.META.get('CONTENT_TYPE') == 'application/json':
            data = request.body
            data_dict = json.loads(data)
            request.data = data_dict


# 统计在线人数
class GetOnlineQuantity(MiddlewareMixin):
    # 请求中间件
    def process_request(self, request):
        ip = request.META['REMOTE_ADDR']  # 获取当前请求ip
        IP_list = list(cache.get('ip_list', []))
        if ip not in IP_list:
            IP_list.append(ip)
        cache.set('ip_list', IP_list, 30)  # 设置缓存
        request.ip_list = cache.get('ip_list')
